const helper = require('../../xci/helper')
const service = require('../../xci/service')
const auth = require('../../xci/auth')
const {plateNumber, phoneNumber} = require('../../xci/validator')
let uploadFiles = []

Page({
  data: {
    openid: '',
    datePickerVisible: false,
    plateNumberPickerVisible: false,
    valueDate: helper.formatDate(new Date()),
    minDate: helper.formatDate(new Date()),
    maxDate: helper.formatDate(helper.addDate(new Date(), 120)),
    form: {
      formName: 'applyForm',
      alignType: 'start',
      labelWidth: '160rpx',
      rightIconSize: 26,
      rightIconColor: '#8c98ae'
    },
    picker: {
      vehicleCategory: [],
      faultCategory: []
    },
    rule: {
      plateNumber: [
        {required: true, message: '请输入车牌号码'},
        {validator: plateNumber, message: '请输入正确的车牌号码'},
      ],
      companyName: {required: true, message: '请输入公司名称'},
      vehicleCategory: {required: true, message: '请选择车辆类型'},
      faultCategory: {required: true, message: '请选择故障类型'},
      faultDesc: {required: true, message: '请输入故障描述'},
      reserveAddress: {required: true, message: '请选择预约地点'},
      reserveDateTimeText: {required: true, message: '请选择预约时间'},
      driverName: {required: true, message: '请输入司机姓名'},
      driverPhone: [
        {required: true, message: '请输入司机电话'},
        {validator: phoneNumber, message: '请输入正确的司机电话'},
      ],
      createName: {required: true, message: '请输入报修人姓名'},
      createPhone: [
        {required: true, message: '请输入报修电话'},
        {validator: phoneNumber, message: '请输入正确的报修电话'},
      ],
    },
    model: {
      plateNumber: '',//车牌号码
      companyName: '', //公司名称
      vehicleCategory: '', //车辆类型
      faultCategory: '', //故障类型
      faultDesc: '', //故障描述
      reserveLongitude: '',//预约地点经度
      reserveLatitude: '',//预约地点纬度
      reserveAddress: '',//预约地点
      reserveDateTimeText: '',//预约时间
      reserveDateTime: '',//预约时间
      driverName: '', //司机姓名
      driverPhone: '', //司机电话
      createName: '', //报修人姓名
      createPhone: '', //报修电话
      openid: '',//报修人Openid
      remark: '', //备注
    },
  },
  async onLoad() {
    wx.lin.initValidateForm(this)
    this.data.openid = await auth.getOpenid()
    const result = await service.repairApply.selectMemberByOpenid(this.data.openid)
    if (result && result.data) {
      this.setData({
        'model.companyName': result.data.company,
        'model.createName': result.data.name,
        'model.createPhone': result.data.phone
      })
    }

    const vehicleCategoryResult = await service.repairApply.selectDicListByCode('wx.mini.vehicleCategory')
    const faultCategoryResult = await service.repairApply.selectDicListByCode('wx.mini.faultCategory')
    this.setData({
      'picker.vehicleCategory': vehicleCategoryResult.data.map(p => p.name),
      'picker.faultCategory': faultCategoryResult.data.map(p => p.name),
    })
  },
  onShow() {
  },
  onSave() {
    const formName = this.data.form.formName
    const tempId = 'aNFhjR6qcxA_e3n59x4F2rJKUNKLYycBBQT1uPCdj8o'
    wx.requestSubscribeMessage({
      tmplIds: [tempId],
      success(res) {
        if (res[tempId] === 'accept') {
          wx.lin.submitForm(formName)
        } else {
          helper.showToast('同意订阅消息后继续')
        }
      },
      fail(err) {
        console.log(err);
      }
    })
  },
  async onSubmit(e) {
    if (e.detail.isValidate === false) return

    //图片上传
    const uploadResult = await helper.uploadFiles(uploadFiles, '/mini/repair-apply',)
    const files = uploadResult.map(p => p.data.url)

    const data = {
      ...this.data.model,
      ...e.detail.values,
      openid: this.data.openid,
      files: files.join(',')
    }
    console.log('submit.Data', data)
    const result = await service.repairApply.insertRepairApply(data)
    if (result.success) {
      await helper.showToast('故障申报成功')
      wx.redirectTo({
        url: `../repair-apply-search/index`
      })
    }
  },
  async onChooseLocation(e) {
    await helper.authorize('scope.userLocation', '需要获取你的位置信息，请确认授权，否则无法使用地图选点功能')
    if (!this.data.model.reserveLongitude) {
      wx.showLoading({title: '正在定位...'})
      const currentLocationResult = await wx.getLocation({}).catch(helper.consoleLog)
      wx.hideLoading()
      if (currentLocationResult) {
        this.data.model.reserveLongitude = currentLocationResult.longitude
        this.data.model.reserveLatitude = currentLocationResult.latitude
      }
    }

    const result = await wx.chooseLocation({
      latitude: this.data.model.reserveLatitude,
      longitude: this.data.model.reserveLongitude
    }).catch(helper.consoleLog)
    console.log('chooseLocation result', result)
    if (result) {
      this.setData({
        'model.reserveLongitude': result.longitude,
        'model.reserveLatitude': result.latitude,
        'model.reserveAddress': result.address,
      })
    }
  },

  onShowDatePicker() {
    this.setData({
      datePickerVisible: true
    })
  },
  onShowPlateNumberPicker() {
    this.setData({
      plateNumberPickerVisible: !this.data.plateNumberPickerVisible
    })
  },

  onPlateNumberPickerChange(e) {
    const val = e.detail.value.join('')
    this.setData({
      'model.plateNumber': val
    })
  },
  onDatePickerChange(e) {
    this.setData({
      'model.reserveDateTimeText': e.detail.displayValue.join(''),
      'model.reserveDateTime': helper.formatDateTime(new Date(e.detail.date))
    })
  },
  onVehicleCategoryChange(e) {
    this.setData({
      // 'model.vehicleCategory': this.data.picker.vehicleCategory[e.detail.value]
      'model.vehicleCategory': e.detail.value
    })
  },
  onFaultCategoryChange(e) {
    this.setData({
      'model.faultCategory': this.data.picker.faultCategory[e.detail.value]
    })
  },
  onImagePickerChange(e) {
    uploadFiles = e.detail.all
  },
})

// id 主键
// plateNumber 车牌号码
// companyName 公司名称
// vehicleCategory 车辆类型
// faultCategory 故障类型
// createDateTime 报修时间
// faultDesc 故障描述
// reserveLongitude 预约地点经度
// reserveLatitude 预约地点纬度
// reserveAddress 预约地点
// reserveDateTime 预约时间
// driverName 司机姓名
// driverPhone 司机电话
// createName 报修人姓名
// createPhone 报修电话
// openid 报修人openid
// replyStatus 回复状态 [未回复_0,已回复_1]
// replyMsg 回复消息
// replyDateTime 回复时间
// replyUser 回复人
// remark 备注
